import db from '../utils/dbconf'
import { SQL_ERROR,RES_ERROR } from '../server.config.js'
import { Random } from 'mockjs'
import md5 from 'md5'
const TABLE_NAME = 'USERS'

export default{
  signin:async ({body:{ username,password }}, res) => {
    try{
      const uinfo = await db.table(TABLE_NAME)
        .where({username})
        .find()
      if(!uinfo.id) return res.send(RES_ERROR('用户不存在'))
      if(md5(password) != uinfo.password) return res.send(RES_ERROR('用户名或密码错误'))
      delete uinfo.password
      delete uinfo.username
      if(uinfo.type === 999){ // 管理员
        const admtoken = Random.string('lower',32)
        Object.assign(global,{ admtoken })
        uinfo.token = admtoken
      }
    	return res.send({
    	  code: 200,
    	  data:uinfo
    	})
    }catch(error){
    	return res.send(SQL_ERROR)
    }
  },
  changepwd:async ({body:{ oldpwd,newpwd }}, res) => {
    try{
      const { id } = res.locals
      const { password,type } = await db.table(TABLE_NAME)
        .where({id})
        .find()
      if(password != md5(oldpwd)) return res.send(RES_ERROR('旧密码错误'))
      await db.table(TABLE_NAME)
        .where({id})
        .update({ password:md5(newpwd) })
      if(type === 999) delete global.admtoken
    	return res.send({ code: 200 })
    }catch(error){
    	return res.send(SQL_ERROR)
    }
  },
  sync: async ({body:{users}},res) => {
    try {
      let data = {}
      for(let uinfo of users){
        const { username } = uinfo
        const id = await db.table(TABLE_NAME).thenAdd(uinfo,{username},false)
        data[username] = id
      }
      return res.send({
        code:200,
        data
      })
    } catch (error) {
      console.log(error)
      return res.send(SQL_ERROR)
    }
  },
  get:async ({query,params}, res) => {
    try{
      const { nicknamelike, usernamelike,size,page } = query
      const { baseid } = params
      const wherefilter = { 
        baseid,
        nickname:['LIKE',`%${nicknamelike||''}%`],
        username:['LIKE',`%${usernamelike||''}%`]
      }
    	const baseinfo = await db.table(TABLE_NAME)
        .where(wherefilter)
        .page(page,size)
        .select()
      const total = await db.table(TABLE_NAME)
        .where(wherefilter)
        .count('id')
      return res.send({
        code:200,
        data:{ baseinfo,total }
      })
    }catch(error){
      console.log(error)
    	return res.send(SQL_ERROR)
    }
  },
}